package paidaxing.blog.user.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import paidaxing.blog.core.annotation.OperationEnumType;
import paidaxing.blog.core.annotation.OperationLog;
import paidaxing.blog.common.result.Result;
import paidaxing.blog.user.dto.LoginRequest;
import paidaxing.blog.user.dto.LoginResultDTO;
import paidaxing.blog.user.dto.UserDTO;
import paidaxing.blog.user.dto.UserRequest;
import paidaxing.blog.user.service.UserService;

/**
 * 用户鉴权控制层
 *
 * @author heefM
 * @date 2025-10-18
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {


    @Autowired
    private UserService userService;

    /**
     * 用户注册接口
     * @param userRequest
     * @return
     */
    @PostMapping("/register")
    public Result<UserDTO> register(@Valid @RequestBody UserRequest userRequest) {
        UserDTO userDTO = userService.register(userRequest);
        return Result.success(userDTO);
    }

    /**
     * 用户登录接口
     * @param request
     * @return
     */
    @OperationLog(type = OperationEnumType.LOGIN)
    @PostMapping("/login")
    public Result<LoginResultDTO> login(@Valid @RequestBody LoginRequest request) {
        if(log.isInfoEnabled()){
            log.info("用户登录接口: {}", request);
        }

        // 业务处理
        LoginResultDTO loginResult = userService.login(request);

        return Result.success(loginResult);

    }

    /**
     * 用户退出登录
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(){
        if(log.isInfoEnabled()){
            log.info("用户退出登录，token: {}", StpUtil.getTokenValue());
        }
        StpUtil.logout();
        if(StringUtils.isBlank(StpUtil.getTokenValue())){
            return Result.failed("退出登录失败!");
        }
        return Result.success("退出登录成功!");
    }


    /**
     * 判断用户是否登录成功
     * @return
     */
    @GetMapping("/isLogin")
    public Result<String> checkLogin(){
        boolean loginResult = StpUtil.isLogin();
        if(loginResult){
           return Result.success("当前会话已经登录!");
        }
        return Result.failed("当前会话没有登录!--请登录!");
    }


    /**
     * 获取当前用户的信息
     * @return
     */
    @SaCheckLogin  //检查是否登录,登录才可获取当前用户信息
    @GetMapping("/profile")
    public Result<UserDTO> getCurrentUser(){
        Object loginId = StpUtil.getLoginId();
        UserDTO userDTO = userService.getCurrentUser(Long.valueOf(String.valueOf(loginId)));
        return Result.success(userDTO);
    }



}
